package com.common.VO;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

import java.io.IOException;
import java.util.List;

/**
 * @author 大静
 * @version 1.0
 * @date 2021-05-07 9:46
 */
@Data
@NoArgsConstructor
@AllArgsConstructor
public class SupermarketResult {
  //    定义jackson对象
  private static final ObjectMapper MAPPER = new ObjectMapper();
  //    查询数据总数量
  private Integer total;
  //    分页查询的list结果
  private List<?> rows;

  public SupermarketResult(Long total, List<?> rows) {
    this.total = total.intValue();
    this.rows = rows;
  }
  /**
   * Object是集合转化
   *
   * @param jsonData json数据
   * @param clazz 集合中的类型
   * @return
   */
  public static SupermarketResult formatToList(String jsonData, Class<?> clazz) {
    try {
      JsonNode jsonNode = MAPPER.readTree(jsonData);
      JsonNode data = jsonNode.get("rows");
      List<?> list = null;
      if (data.isArray() && data.size() > 0) {
        try {
          list =
              MAPPER.readValue(
                  data.traverse(),
                  MAPPER.getTypeFactory().constructCollectionType(List.class, clazz));
          return new SupermarketResult(jsonNode.get("total").intValue(), list);
        } catch (IOException e) {
          e.printStackTrace();
        }
      }
    } catch (JsonProcessingException e) {
      e.printStackTrace();
    }
    return null;
  }
}
